package chapter10_Advanced._thread;

/**
 * ClassName: WindowsTest
 * Package: chapter10_Advanced._thread
 * Description:
 *
 * 窗口买票--多线程--使用同步代码块解决线程安全问题
 *
 * @Author SherryAn
 * @Create 2025/7/30 20:11
 */
public class WindowsTest {
    public static void main(String[] args) {
        SaleTicket s=new SaleTicket();
        Thread t1=new Thread(s);
        Thread t2=new Thread(s);
        Thread t3=new Thread(s);

        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");

        t1.start();
        t2.start();
        t3.start();
    }
}

class SaleTicket implements Runnable{
    int ticket=100;

    Object obj=new Object();

    @Override
    public void run() {
        while (true){

            synchronized (obj){//要想保障安全性，obj必须是唯一的

                if (ticket>0){
                    try {
                        Thread.sleep(5);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"售票，票号为："+ticket);
                    ticket--;
                }else {
                    break;
                }
            }
        }
    }
}
